package com.yunkaweilai.android.activity.shop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.SimpleInterface;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.model.shop.ShopInfoDiyModel;
import com.yunkaweilai.android.model.shop.ShopInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.shop.ShopDelDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 普通商品查看
 * Created by Administrator on 2017/6/14.
 */

public class PtShopActivity extends BaseActivity implements SimpleInterface {


    @BindView(R.id.id_shop_img)
    ImageView idShopImg;
    @BindView(R.id.id_tv_shop_name)
    TextView idTvShopName;
    @BindView(R.id.id_tv_shop_type)
    TextView idTvShopType;
    @BindView(R.id.id_tv_shop_num)
    TextView idTvShopNum;
    @BindView(R.id.id_tv_abbreviation_left)
    TextView idTvAbbreviationLeft;
    @BindView(R.id.id_tv_abbreviation)
    TextView idTvAbbreviation;
    @BindView(R.id.id_tv_company_left)
    TextView idTvCompanyLeft;
    @BindView(R.id.id_tv_company)
    TextView idTvCompany;
    @BindView(R.id.id_llayout_diy)
    LinearLayout idLlayoutDiy;
    @BindView(R.id.id_tv_sell_price)
    TextView idTvSellPrice;
    @BindView(R.id.id_tv_purchase_price)
    TextView idTvPurchasePrice;
    @BindView(R.id.id_llayout_purchase)
    LinearLayout idLlayoutPurchase;
    @BindView(R.id.id_view_purchase)
    View idViewPurchase;
    @BindView(R.id.id_tv_kucun)
    TextView idTvKucun;
    @BindView(R.id.id_llayout_stock)
    LinearLayout idLlayoutStock;
    @BindView(R.id.id_view_kucun)
    View idViewKucun;
    @BindView(R.id.id_tv_warning)
    TextView idTvWarning;
    @BindView(R.id.id_llayout_warning)
    LinearLayout idLlayoutWarning;
    @BindView(R.id.id_view_warning)
    View idViewWarning;
    @BindView(R.id.id_tv_commission)
    TextView idTvCommission;
    @BindView(R.id.id_llayout_commission)
    LinearLayout idLlayoutCommission;
    @BindView(R.id.id_tv_fixed_discount)
    TextView idTvFixedDiscount;
    @BindView(R.id.id_tv_fold)
    TextView idTvFold;
    @BindView(R.id.id_tv_fixed_integral)
    TextView idTvFixedIntegral;
    @BindView(R.id.id_tv_remarks)
    TextView idTvRemarks;
    @BindView(R.id.id_llayout_remark)
    LinearLayout idLlayoutRemark;
    @BindView(R.id.id_view_remark)
    View idViewRemark;
    @BindView(R.id.content_view)
    ScrollView contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_llayout_special)
    LinearLayout idLlayoutSpecial;
    @BindView(R.id.id_llayout_del)
    TextView idLlayoutDel;
    @BindView(R.id.id_tv_qiyong)
    TextView mTextview;
    @BindView(R.id.id_line_out)
    LinearLayout lineOut;
    private String shop_id;
    public static final String SHOP_ID = "SHOP_ID";
    private ShopInfoModel shopInfoModel;//商品信息
    private AppRuleModel.DataBean.InfoBean appRuleModel;
    private boolean diyisShow = false;//是否获取到diy
    private Gson gson = new Gson();
    private ArrayList<ShopInfoDiyModel.DataBean.InfoBean> diyList = new ArrayList<>();
    private Map<String, String> diymap = new HashMap<>();
    private LayoutInflater inflater;
    private UserInfoModel.DataBean.StoreEmployeeInfoBean userInfo;
    private boolean ready = false;

    public static void actionStart(Context context, String shop_id) {
        Intent intent = new Intent(context, PtShopActivity.class);
        intent.putExtra(SHOP_ID, shop_id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pt_shop);
        ButterKnife.bind(this);
        inflater = getLayoutInflater();
        appRuleModel = BaseApplication.getAppRuleModel();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Intent intent = getIntent();
        shop_id = intent.getStringExtra(SHOP_ID);
        userInfo = BaseApplication.getUserInfo();
        if (userInfo.isIs_first()) {
            idLlayoutDel.setVisibility(View.VISIBLE);
            TitleBuilder titleBuilder = new TitleBuilder(this).setLeftImage(R.mipmap.ic_go_back).setTitleText("商品详细");
            if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                titleBuilder.setRightText("修改");
            }
        } else {
            idLlayoutDel.setVisibility(View.GONE);
            new TitleBuilder(this).setLeftImage(R.mipmap.ic_go_back).setTitleText("商品详细");
        }

        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDiyHttp();
            }
        });
        initDiyHttp();
    }


    private void initDiyHttp() {
        HttpRequest.postUrl(Api.SHOP_DIY_LIST)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        diyisShow = Utils.checkCode(mAc, json);
                        if (diyisShow) {
                            ShopInfoDiyModel shopInfoDiyModel = gson.fromJson(json, ShopInfoDiyModel.class);
                            initAddView(shopInfoDiyModel);
                        }
                        initHttp();
                    }

                    @Override
                    public void onError(Exception e) {
                        diyisShow = false;
                        initHttp();
                    }
                });
    }

    //处理自定义属性
    private void initAddView(ShopInfoDiyModel shopInfoDiyModel) {
        idLlayoutDiy.removeAllViews();
        diyList.clear();
        diyList.addAll(shopInfoDiyModel.getData().getInfo());
        for (int i = 0; i < diyList.size(); i++) {
            LinearLayout view = (LinearLayout) inflater
                    .inflate(R.layout.view_member_info_diy_txt, null);
            TextView tvName = (TextView) view.findViewById(R.id.id_tv_name);
            ((TextView) view.findViewById(R.id.id_tv_content)).setText("");
            tvName.setText(diyList.get(i).getField_name());
            idLlayoutDiy.addView(view);
        }
        if (diyList.size() == 0) {
            idLlayoutDiy.setVisibility(View.GONE);
        } else {
            idLlayoutDiy.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void refreshInfo(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.SHOP_INFO_REFRESH) {
                if (event.flag) {
                    idMultipleStatusView.showLoading();
                    lineOut.setVisibility(View.GONE);
                    initDiyHttp();
                }
            }
        }
    }


    private void initHttp() {
        HttpRequest.postUrl(Api.PT_SHOP_INFO)
                .addParams("id", shop_id)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(PtShopActivity.this, json);
                        if (checkCode) {
                            shopInfoModel = gson.fromJson(json, ShopInfoModel.class);
                            initView();
                            ready = true;
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                            if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                                lineOut.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    //商品信息填充
    @SuppressLint("SetTextI18n")
    private void initView() {
        ShopInfoModel.DataBean.InfoBean info = shopInfoModel.getData().getInfo();
        Utils.shopInfoImg(mAc, info.getGoods_image(), idShopImg);
        idTvShopName.setText(info.getGoods_name() + "");//名称
        idTvShopType.setText("类别：" + info.getGoods_category_name() + "    条码：" + info.getGoods_sku());
        idTvShopNum.setText("库存：" + info.getMay_use_stock() + "  已销售：" + info.getSuccess_num());
        idTvAbbreviation.setText(info.getGoods_code() + "");//简称
        idTvCompany.setText(info.getUnit() + "");//单位
        if (info.getSelect_specToArray().size() > 0) {
            idTvSellPrice.setText("多规格");//销售价格
            idTvPurchasePrice.setText("多规格");//进货价格
            idTvWarning.setText("多规格");//预警值
        } else {
            idTvSellPrice.setText(info.getGoods_shop_price() + "");//销售价格
            idTvPurchasePrice.setText(info.getGoods_purchase_price());//进货价格
            idTvWarning.setText(info.getGoods_warning() + "");//预警值
        }
        idTvKucun.setText(info.getMay_use_stock());//仓库库存
        idTvCommission.setText(Utils.ManageMoney(info.getGoods_reward()));//员工提成
        switch (info.getStatus()) {//是否启用
            case "1":
                mTextview.setText("使用中");
                break;
            case "0":
                mTextview.setText("停用中");
                break;
        }
        if (shopInfoModel.getData().getSpecialData() != null) {
            if ("1".equals(shopInfoModel.getData().getSpecialData().getIs_new_special())) {
                //不显示特殊商品
                idLlayoutSpecial.setVisibility(View.GONE);
            } else {
                idLlayoutSpecial.setVisibility(View.VISIBLE);
            }
        } else {
            idLlayoutSpecial.setVisibility(View.GONE);
        }
        if ("0".equals(info.getIs_special_discount())) {//是否启用特殊折扣
            idTvFixedDiscount.setText("否");
        } else {
            idTvFixedDiscount.setText(info.getSpecial_discount() + "%");
        }
        if ("0".equals(info.getIs_discount_to_discount())) {//是否开启折上折
            idTvFold.setText("否");
        } else {
            idTvFold.setText("是");
        }
        if ("0".equals(info.getIs_special_points())) {//是否固定积分
            idTvFixedIntegral.setText("否");
        } else {
            idTvFixedIntegral.setText(info.getSpecial_points());
        }

        setDiyView();
    }

    //对会员存在的自定义属性进行设置
    private void setDiyView() {
        if (diyisShow) {
            ArrayList<ShopInfoModel.DataBean.InfoBean.AppDIYFieldModel> diyfield_list = shopInfoModel.getData().getInfo().getAppDIYField();
            for (int i = 0; i < diyfield_list.size(); i++) {
                ShopInfoModel.DataBean.InfoBean.AppDIYFieldModel diyfieldListBean = diyfield_list.get(i);
                for (int j = 0; j < diyList.size(); j++) {
                    if (diyList.get(j).getId().equals(diyfieldListBean.getDiy_field_id())) {
                        View childAt = idLlayoutDiy.getChildAt(j);
                        ((TextView) childAt.findViewById(R.id.id_tv_content)).setText(diyfieldListBean.getDiy_field_value());
                        ((TextView) childAt.findViewById(R.id.id_tv_content)).setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    }
                }
            }
        }
    }

    @OnClick({R.id.titlebar_iv_left, R.id.titlebar_tv_right, R.id.id_shop_img, R.id.id_llayout_del, R.id.id_btn_out, R.id.id_btn_put, R.id.id_btn_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_shop_img:
                Utils.ImageEnlage(mAc, "2", shopInfoModel.getData().getInfo().getGoods_image(), "");
                break;
            case R.id.titlebar_iv_left:
                finish();
                break;
            case R.id.titlebar_tv_right:
                if (ready) {
                    if (shopInfoModel.getData().getInfo().getSelect_specToArray().size() > 0) {
                        showToast("多规格商品请到PC端修改！");
                    } else {

                        if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                            UpdatePtShopActivity2.actionStart(this, shop_id);
                        }
                    }
                }

                break;
            case R.id.id_llayout_del://删除商品
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                    ShopDelDialog dialog = new ShopDelDialog(mAc, shop_id, this);
                    dialog.show();
                } else {
                    showToast("没有删除权限");
                }
                break;
            case R.id.id_btn_out:
                if (shopInfoModel.getData().getInfo().getSelect_specToArray().size() > 0) {
                    showToast("多规格商品请到PC端修改！");
                } else {
                    if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                        PtShopPandianActivity.actionStart(this, shopInfoModel, PtShopPandianActivity.TYPE_OUT);
                    }
                }
                break;
            case R.id.id_btn_put:
                if (shopInfoModel.getData().getInfo().getSelect_specToArray().size() > 0) {
                    showToast("多规格商品请到PC端修改！");
                } else {
                    if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                        PtShopPandianActivity.actionStart(this, shopInfoModel, PtShopPandianActivity.TYPE_ADD);
                    }
                }
                break;
            case R.id.id_btn_change:
                if (shopInfoModel.getData().getInfo().getSelect_specToArray().size() > 0) {
                    showToast("多规格商品请到PC端修改！");
                } else {
                    if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                        PtShopPandianActivity.actionStart(this, shopInfoModel, PtShopPandianActivity.TYPE_CHANGE);
                    }
                }
                break;
        }
    }

    @Override
    public void nothing() {
        finish();
    }
}
